import behaviors from "../../../../../config/behaviors";

Component({
  behaviors: [behaviors],
  properties: {
    product: {
      type: Object,
      value: {},
      observer(newVal, oldVal, changedPath) {
        if (Object.keys(newVal).length > 0) {
          this._buttonText()
          this._defineSkuList()
          this._currentImage()
          this._currentPrice()
          this._currentStock()
          this._totalPrice()
          this._totalScore()
        }
      }
    },
    type: Number
  },
  data: {
    openDone: false,
    buttonText: '',
    currentImage: '',
    currentStock: 0,
    currentPrice: 0,
    // show all sku or define sku
    showAllSku: false,
    // [id, id]
    selectedList: [],
    // [{id, text}]
    selectedText: [],
    // if selectedSku.length > 1, maybe Choice is not complete
    // [{}, {}]
    selectedSku: [],
    // selectedSku[0]
    whichSku: {},
    totalQuantity: 1,
    defineSkuList: [],
    totalPrice: 0,
    totalScore: 0
  },
  methods: {
    closePop() {
      this.reset()
      this.triggerEvent('closePop')
    },
    reset() {
      this.setData({
        selectedList: [],
        selectedText: [],
        whichSku: {}
      })

      const product = { ...this.properties.product }
      product.skuName.forEach(x => {
        x.values.forEach(y => {
          // this.$set(y, 'selected', undefined)
          // this.$set(y, 'disabled', undefined)
          y.selected = undefined
          y.disabled = undefined
        })
      })
      this.triggerEvent('changeProduct', { product })
    },

    subQuantity() {
      if (this.data.totalQuantity > 1) {
        this.setData({
          totalQuantity: this.data.totalQuantity - 1
        })
        this._totalPrice()
      }
    },

    addQuantity() {
      if (this.data.totalQuantity < this.data.currentStock) {
        this.setData({
          totalQuantity: this.data.totalQuantity + 1
        })
        this._totalPrice()
      }
    },

    _totalPrice() {
      const total = this.data.currentPrice * this.data.totalQuantity
      this.setData({
        totalPrice: total
      })
    },

    _totalScore() {
      let total = 0
      if (this.properties.product.scoreCost) {
        total = this.properties.product.scoreCost.total * this.data.totalQuantity
      }
      this.setData({
        totalScore: total
      })
    },

    _buttonText() {
      let text = ''
      switch (this.properties.type) {
        case 1:
          text = '添加到购物车'
          break
        case 2:
          text = '立即购买'
          break
        case 3:
          text = '发起拼团'
          break
        case 4:
          text = '参与此团'
          break
        case 5:
          text = '随机拼团'
          break
        default:
          text = ''
      }
      this.setData({
        buttonText: text
      })
    },

    // all defined sku values list
    _defineSkuList() {
      const list = this.properties.product.sku.map(x => x.sku_values)
      const all = list.reduce((total, current) => {
        return total.concat(current)
      })
      this.setData({ defineSkuList: all })
    },

    _currentImage() {
      let image = ''
      if (this.data.selectedList.length > 0) {
        if (this.data.whichSku.image && this.data.whichSku.image.thumbnail_path) {
          image = this.data.whichSku.image.thumbnail_path
        }
      } else {
        if (this.properties.product.mainImage && this.properties.product.mainImage.thumbnail_path) {
          image = this.properties.product.mainImage.thumbnail_path
        }
      }
      this.setData({ currentImage: image })
    },

    _currentStock() {
      let price = 0
      if (this.data.selectedList.length > 0) {
        price = this.data.whichSku.price
      } else {
        price = this.data.product.price
      }
      this.setData({
        currentPrice: price
      })
    },

    _currentPrice() {
      let stock = 0
      if (this.data.selectedList.length > 0) {
        stock = this.data.whichSku.stock
      } else {
        stock = this.data.product.stock
      }
      this.setData({
        currentStock: stock
      })
    },

    selectValue(e) {
      const o = e.currentTarget.dataset.value
      if (o.disabled && this.properties.product.skuName.length > 1) {
        return
      }

      const product = { ...this.properties.product }

      // 1. myself
      let skuNameIndex, selected
      product.skuName.forEach((x, index) => {
        x.values.forEach(y => {
          if (y.id === o.id) {
            // this.$set(o, 'selected', !o.selected)
            o.selected = !o.selected
            // 小程序改变值的方式和vue不一样
            y.selected = o.selected
            skuNameIndex = index
            selected = o.selected
          }
        })
      })

      // 2. level
      if (skuNameIndex !== undefined) {
        product.skuName[skuNameIndex].values.forEach(x => {
          if (selected && x.id !== o.id) {
            // this.$set(x, 'selected', undefined)
            x.selected = undefined
          }
        })
      }

      // 3. admin set
      const selectedValues = this.selectedValues(true)
      const list = product.sku.filter(x => selectedValues.every(y => x.sku_values.includes(y.id)))
      this.setData({ selectedSku: list })
      const listValues = []
      list.forEach(x => {
        x.sku_values.forEach(y => {
          listValues.push(y)
        })
      })
      product.skuName.forEach(x => {
        x.values.forEach(y => {
          if (!listValues.includes(y.id)) {
            // this.$set(y, 'disabled', true)
            y.disabled = true
          } else {
            // this.$set(y, 'disabled', undefined)
            y.disabled = undefined
          }
        })
      })

      // 4 selected display
      this.setData({
        selectedText: selectedValues.map(x => x.text),
        selectedList: selectedValues.map(x => x.id)
      })

      if (this.data.selectedSku.length > 0) {
        const whichSku = this.data.selectedSku[0]
        this.setData({ whichSku })
      }

      this._currentStock()
      this._currentPrice()

      this.triggerEvent('changeProduct', { product })
    },

    selectedValues(appendText = false) {
      const list = []
      this.properties.product.skuName.forEach(x => {
        x.values.forEach(y => {
          if (y.selected) {
            if (appendText) {
              list.push({ id: y.id, text: y.value })
            } else {
              list.push(y.id)
            }
          }
        })
      })
      return list
    },

    // submit
    submit() {
      if (this.data.selectedList.length < 1) {
        return wx.showToast({ title: '请选择规格', icon: 'error' })
      }
      if (this.data.selectedSku.length > 1) {
        return wx.showToast({ title: '请选择完整', icon: 'error' })
      }

      // type
      let emit
      switch (this.properties.type) {
        case 1:
          emit = 'addCart'
          break
        case 2:
          emit = 'buy'
          break
        case 3:
          emit = 'createGroup'
          break
        case 4:
          emit = 'joinGroup'
          break
        case 5:
          emit = 'randomGroup'
          break
        default:
          emit = ''
      }

      if (emit.length > 0) {

        if (this.data.totalQuantity > this.data.currentStock) {
          return wx.showToast({ title: '库存不足', icon: 'error' })
        }

        this.triggerEvent(emit, {
          quantity: this.data.totalQuantity,
          price: this.data.currentPrice,
          score_cost: this.data.product.scoreCost ? this.data.product.scoreCost.total : 0,
          product_sku_id: this.data.whichSku.id,
          selected_sku_value: this.data.selectedList,
          selected_sku_text: this.data.selectedText
        })

        this.closePop()
      }
    }

  },
  lifetimes: {

    created() {
      setTimeout(() => {
        this.setData({ openDone: true })
      }, 50)
    },

    attached() {

    }
  }
});
